package com.arsn.dome.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.arsn.dome.entity.ImageData;
import com.arsn.dome.entity.UserExcel;
import com.arsn.dome.service.UserService;
import com.arsn.dome.vo.UserVo;
import lombok.AllArgsConstructor;
import org.apache.commons.codec.Charsets;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户控制层
 * @author zhongrj
 * @time 2021-05-10
 */
@RestController
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 导出报表，分 sheet 导出
     * @param response
     */
    @GetMapping("/report-user")
    public void reportUserExcel(HttpServletResponse response){
        //查询用户所有数据
        List<UserExcel> users = userService.selUserList();
        System.out.println("users = " + users);
        //查询用户统计数据
        List<UserVo> userVos = userService.selUserPie();
        //导出报表
        exportForms(users,userVos,response);
    }

    /**
     * 导出报表
     * @param users 用户列表数据
     * @param userVos 用户统计数据
     */
    private void exportForms(List<UserExcel> users, List<UserVo> userVos,HttpServletResponse response) {
        //创建jfreechart 画图对象
        DefaultPieDataset pds = new DefaultPieDataset();
        //以饼图为例
        //遍历统计数据，将数据保存到饼图对象中
        for (UserVo userVo:userVos) {
            pds.setValue(userVo.getSex(),userVo.getNum());
        }

        //声明excelWriter对象user
        ExcelWriter excelWriter  = null;
        try {
            // 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
            JFreeChart chart = ChartFactory.createPieChart("用户数据统计图", pds, false, false, true);
            // 如果不使用Font,中文将显示不出来
            Font font = new Font("宋体", Font.BOLD, 24);
            // 设置图片标题的字体
            chart.getTitle().setFont(font);
            // 得到图块,准备设置标签的字体
            PiePlot plot = (PiePlot) chart.getPlot();
            // 设置标签字体
            plot.setLabelFont(font);
            plot.setStartAngle(new Float(3.14f / 2f));
            // 设置plot的前景色透明度
            plot.setForegroundAlpha(0.7f);
            // 设置plot的背景色透明度
            plot.setBackgroundAlpha(0.0f);
            // 设置标签生成器(默认{0})
            // {0}:key {1}:value {2}:百分比 {3}:sum
            plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1}占{2})"));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            //创建图片数据集合，对象
            ArrayList<ImageData> imageDatas = new ArrayList<>();
            ImageData imageData = new ImageData();
            try {
                // 将图表写入到ByteArrayOutputStream流中
                ChartUtilities.writeChartAsJPEG(bos, chart, 800, 700);
                //将字节数组输出流写入到输入流中
                InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
                //excel 文件名称
                String fileName = "用户统计报表" + System.currentTimeMillis();
                //封装数据到图表
                imageData.setInputStream(inputStream);
                imageDatas.add(imageData);

                //设置响应体
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding(Charsets.UTF_8.name());
                fileName = URLEncoder.encode(fileName, Charsets.UTF_8.name());
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //写入
                excelWriter  = EasyExcel.write(response.getOutputStream()).build();

                //shell0
                WriteSheet writeSheet = EasyExcel.writerSheet(0, "图表").head(ImageData.class).build();
                excelWriter.write(imageDatas, writeSheet);

                //shell1
                WriteSheet writeSheet0 = EasyExcel.writerSheet(1, "数据列表").head(UserExcel.class).build();
                excelWriter.write(users, writeSheet0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //完成后会关闭流
            excelWriter.finish();
        }
    }

}
